package com.xuyuan.remote;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JDKHttpUtil {
    private static final String EXAMPLE_URL = "http://www.example.com";
    public static void main(String[] args) throws Exception {
        // 1、获取HttpURLConnection
        URL url = new URL(EXAMPLE_URL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");

        // 2、设置请求内容
        httpURLConnection.setRequestProperty("Accept", "application/json");
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setInstanceFollowRedirects(true);
        httpURLConnection.setConnectTimeout(5000);
        httpURLConnection.setReadTimeout(10000);

        // 3、发送请求
        httpURLConnection.connect();

        // 4、处理结果
        int responseCode = httpURLConnection.getResponseCode();
        if (responseCode == 200) {
            // TODO 自定义序列化工具处理响应
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine).append("\r");
            }
            in.close();
            System.out.println("Response Body: " + response);
        }

        // 5、断开连接
        httpURLConnection.disconnect();
    }
}
